<template>
  <el-upload
    class="avatar-uploader"
    action=""
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="uploadImage"
  >
    <img v-if="value" :src="value" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>

<script>
import COS from 'cos-js-sdk-v5'
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  methods: {

    beforeAvatarUpload(file) {
      const isJPG = ['image/jpeg', 'image/jpg', 'image/gif', 'image/png'].includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片格式不正确!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    //   return true
    },
    uploadImage(xxx) {
      const cos = new COS({
        SecretId: 'AKIDlcOxqiq22vr8oLf1DSXMuCoWIvNfyc3S',
        SecretKey: 'JM9ydEepkO90jGWWGzMVVJ6j8Vhkrsu3'
      })
      cos.putObject({
        Bucket: '94-web-hr-1324718841',
        Region: 'ap-guangzhou',
        Key: xxx.file.name,
        StorageClass: 'STANDARD',
        Body: xxx.file
      }, (err, data) => {
        // console.log(data)
        if (err) {
          // console.log(err)
        } else {
          this.$emit('input', 'http://' + data.Location) // 将地址返回了
        }
      })
      //   cos.uploadFile({
      //     Bucket: '94-web-hr-1324718841',
      //     Region: 'ap-guangzhou',
      //     Key: xxx.file.name,
      //     StorageClass: 'STANDARD',
      //     Body: xxx.file,
      //     SliceSize: 1024 * 1024 * 5, /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
      //     onProgress: function(progressData) {
      //       console.log(JSON.stringify(progressData))
      //     }

    //   }, (err, data) => {
    //     console.log(err)
    //     console.log(data)
    //     // if (data.statusCode === 200 && data.Location) {
    //     //   // 拿到了腾讯云返回的地址
    //     //   // 通过input自定义事件将地址传出去
    //     //   this.$emit('input', 'http://' + data.Location) // 将地址返回了
    //     // } else {
    //     //   this.$message.error(err.Message) // 上传失败提示消息
    //     // }
    //   })
    }

  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
